<template>
  <div>
    <div class="topic-manage-header">
      <h2>题目管理</h2>
      <div class="topic-manage-actions">
        <el-button type="primary" @click="handleAdd">添加题目</el-button>
        <el-button type="primary" @click="handleFile">导入题目</el-button>
        <el-button type="danger" :disabled="selectedRows.length === 0" @click="handleBatchDelete">批量删除</el-button>
      </div>
    </div>

    <ManageTable :tableConfig="tableConfig" @selection-change="handleSelectionChange" @sort-change="handleSortChange">
      <!-- 操作列插槽 -->
      <template #operation="{ row }">
        <el-button type="primary" size="small" @click="handleEdit(row)">编辑</el-button>
        <el-button type="danger" size="small" @click="handleDelete(row)">删除</el-button>
      </template>
    </ManageTable>

    <!-- 添加/编辑题目对话框 -->
    <el-dialog :title="isEdit ? '编辑题目' : '添加题目'" v-model="dialogVisible" width="500px">
      <el-form :model="formData" label-width="80px">
        <el-form-item label="题目">
          <el-input v-model="formData.topic" placeholder="请输入题目"></el-input>
        </el-form-item>
        <el-form-item label="答案">
          <el-input v-model="formData.answer" type="textarea" :rows="3" placeholder="请输入答案"></el-input>
        </el-form-item>
        <el-form-item label="类型">
          <el-select v-model="formData.type" placeholder="请选择难度">
            <el-option label="简答题" value="简答题"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="领域">
          <el-select v-model="formData.area" placeholder="请选择难度">
            <el-option label="HTML" value="HTML"></el-option>
            <el-option label="CSS" value="CSS"></el-option>
            <el-option label="javascript" value="javascript"></el-option>
            <el-option label="Vue" value="Vue"></el-option>
            <el-option label="React" value="React"></el-option>
            <el-option label="java script" value="javascript"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="难度">
          <el-select v-model="formData.difficulty" placeholder="请选择难度">
            <el-option label="简单" value="简单"></el-option>
            <el-option label="中等" value="中等"></el-option>
            <el-option label="困难" value="困难"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="isEdit ? updateTopic() : submitForm()">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.topic-manage-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.topic-manage-actions {
  display: flex;
  gap: 10px;
}
</style>

<script lang="ts" setup>
import { ref, onMounted, computed } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import ManageTable from '@/components/basic/ManageTable.vue';
import type { TableConfig } from '@/components/basic/ManageTable.vue';

// 题目数据
const topics = ref<any[]>([]);
// 加载状态
const loading = ref(false);
// 选中的行
const selectedRows = ref<any[]>([]);

// 获取所有题目
const fetchTopics = async () => {
  loading.value = true;
  try {
    const response = await $fetch('/api/topics');
    console.log('API响应数据:', response);
    topics.value = response as any[];
    console.log('设置后的topics值:', topics.value);
    console.log('tableConfig计算值:', tableConfig.value);

  } catch (error) {
    console.error('获取题目列表失败:', error);
    ElMessage.error('获取题目列表失败');
  } finally {
    loading.value = false;
  }
};

// 表格配置
const tableConfig = computed(() => {
  console.log('重新计算tableConfig，当前topics:', topics.value);
  return {
    data: topics.value,
    columns: [
      { prop: 'topic', label: '题目', minWidth: 150 },
      { prop: 'answer', label: '答案', minWidth: 150 },
      { prop: 'type', label: '类型', width: 100 },
      { prop: 'area', label: '领域', width: 100, sortable: true },
      { prop: 'difficulty', label: '难度', width: 100 }
    ],
    showIndex: true,
    showSelection: true,
    border: true,
    stripe: true,
    loading: loading.value,
    operationColumn: {
      label: '操作',
      width: 150,
      align: 'center'
    }
  } as TableConfig;
});

// 处理选择变化
const handleSelectionChange = (selection: any[]) => {
  selectedRows.value = selection;
};

// 处理排序变化
const handleSortChange = (sort: any) => {
  console.log('排序变化:', sort);
  // 这里可以根据排序结果重新排序数据
};

// 添加题目对话框
const dialogVisible = ref(false);
const formData = ref({
  topic: '',
  answer: '',
  type: '',
  area: '',
  difficulty: '简单'
});

// 打开添加题目对话框
const handleAdd = () => {
  dialogVisible.value = true;
  formData.value = {
    topic: '',
    answer: '',
    type: '',
    area: '',
    difficulty: '简单'
  };
};

// 提交表单
const submitForm = async () => {
  try {
    await $fetch('/api/topics', {
      method: 'POST',
      body: formData.value
    });
    ElMessage.success('添加题目成功');
    dialogVisible.value = false;
    fetchTopics(); // 重新获取题目列表
  } catch (error) {
    console.error('添加题目失败:', error);
    ElMessage.error('添加题目失败');
  }
};

// 批量删除
const handleBatchDelete = async () => {
  if (selectedRows.value.length === 0) return;

  try {
    await ElMessageBox.confirm('确定要删除选中的题目吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });

    const deletePromises = selectedRows.value.map(row => {
      return $fetch(`/api/topics/${row._id}`, {
        method: 'DELETE'
      });
    });

    await Promise.all(deletePromises);
    ElMessage.success('删除成功');
    fetchTopics(); // 重新获取题目列表
    selectedRows.value = [];
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除题目失败:', error);
      ElMessage.error('删除题目失败');
    }
  }
};

// 处理编辑
const isEdit = ref(false);
const editId = ref('');

const handleEdit = (row: any) => {
  dialogVisible.value = true;
  isEdit.value = true;
  editId.value = row._id;
  formData.value = { ...row };
};

// 更新题目
const updateTopic = async () => {
  try {
    await $fetch(`/api/topics/${editId.value}`, {
      method: 'PUT',
      body: formData.value
    });
    ElMessage.success('更新题目成功');
    dialogVisible.value = false;
    isEdit.value = false;
    fetchTopics(); // 重新获取题目列表
  } catch (error) {
    console.error('更新题目失败:', error);
    ElMessage.error('更新题目失败');
  }
};

// 处理删除
const handleDelete = async (row: any) => {
  try {
    await ElMessageBox.confirm('确定要删除该题目吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });

    await $fetch(`/api/topics/${row._id}`, {
      method: 'DELETE'
    });
    ElMessage.success('删除成功');
    fetchTopics(); // 重新获取题目列表
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除题目失败:', error);
      ElMessage.error('删除题目失败');
    }
  }
};

// 导入题目文件
const handleFile = () => {
  // 文件导入功能，可以后续实现
  ElMessage.info('文件导入功能开发中');
};

// 页面加载时获取题目列表
onMounted(() => {
  fetchTopics();
});
</script>